package com.weixing.mall.provider.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.ResultCodeEnum;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.msg.*;
import com.weixing.mall.core.utils.CommonUtil;
import com.weixing.mall.core.validation.Mobile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: kfc
 * @Description: <br/>
 * Date:Create in 2019/5/30 14:57
 * @Modified By:
 */
@RestController
@RequestMapping("auth")
@Api(value = "短信验证码发送Controller", tags = "短信验证码")
@Validated
public class VerifyCodeController extends BaseController {
    @Autowired
    private DefaultKaptcha producer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;




    @ApiOperation(value = "生成图形验证码", notes = "会员注册生成图形验证码")
    @PostMapping(value = "/captcha")
    public Result captcha() throws IOException {

        String utoken = CommonUtil.fmtUuid();
        // 生成文字验证码

        String verifyCode = producer.createText();
        String key = GlobalConstant.REDIS_PRE_CODE + utoken;
//        // 有效期10分钟
        stringRedisTemplate.opsForValue().set(key, verifyCode, 10, TimeUnit.MINUTES);
        // 生成图片验证码
        ByteArrayOutputStream outputStream = null;
//        System.out.println("status:" + verifyCode);
        BufferedImage image = producer.createImage(verifyCode);

        outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        Map<String ,String> captcha = new HashMap<>();
        captcha.put("utoken",utoken);
        captcha.put("img",encoder.encode(outputStream.toByteArray()));
        return ResultUtil.success(captcha);
    }

    @PostMapping("checkCaptcha")
    public Result check(HttpServletRequest request,
                        @NotNull(message = "请填写图形验证码") String captcha){
        String key = GlobalConstant.REDIS_PRE_CODE + request.getHeader(GlobalConstant.FIELD_UTOKEN);
        String verifyCode_redis = stringRedisTemplate.opsForValue().get(key);
        if (io.micrometer.core.instrument.util.StringUtils.isBlank(verifyCode_redis)){
            return ResultUtil.error(ResultCodeEnum.CODE_10011007);
        }
        if (captcha.equalsIgnoreCase(verifyCode_redis)){
            // 校验通过清除redis
            stringRedisTemplate.delete(key);
        }else{
            return ResultUtil.error(ResultCodeEnum.CODE_10011005);
        }
        return ResultUtil.success();
    }


    @ApiOperation(value = "发送短信")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", paramType = "form", dataType = "string")
    })
    @PostMapping("sms")
    public Result sendRegisterMsg(
            @Mobile(message = "手机号格式不正确")
            @RequestParam String mobile,
            @NotNull(message = "图形验证码不能为空")
            @RequestParam String imageCode,
            HttpServletRequest request
    ) {

        // 校验图形验证码是否正确
        String key = GlobalConstant.REDIS_PRE_CODE + request.getHeader(GlobalConstant.FIELD_UTOKEN);
        String verifyCode_redis = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(verifyCode_redis)){
            return ResultUtil.error(ResultCodeEnum.CODE_10011007);
        }
        if (imageCode.equalsIgnoreCase(verifyCode_redis)){
            // 校验通过清除redis
            stringRedisTemplate.delete(key);
        }else{
            return ResultUtil.error(ResultCodeEnum.CODE_10011005);
        }
        // 生成验证码
        String verifyCode = CommonUtil.genVerifyCode(6);
        SmsParam param = new VerifyCodeParam(verifyCode);
        Msg msg = new Msg(MsgBizEnum.REGISTER_USER, mobile, param);
        MsgResult response = MsgUtil.sendMsg(msg);
        if (response.isSuccess()) {
            String smsKey = GlobalConstant.REDIS_PRE_SMS + mobile;
            // 有效期10分钟
            stringRedisTemplate.opsForValue().set(smsKey, verifyCode, 10,TimeUnit.MINUTES);
        }
        return response.isSuccess() ? ResultUtil.success() : ResultUtil.error();
    }
}
